<?php

namespace App\Http\Middleware;

use Closure;
use Exception;

/**
 * 全局异常处理
 * Class HandleExceptionMiddleware
 * @package App\Http\Middleware
 */
class HandleExceptionMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        try {
            if (env('IS_FORMAT_EXCEPTION', true) && $response->exception) {
                $response->setContent(ApiReturn(RETURN_FAIL, $response->exception->getMessage(), $this->handleErrorInfo($response->exception), $response->status()));
            }
        } catch (\Throwable $e) {

        }

        return $response;
    }

    /**
     * 处理异常信息
     * @param Exception $exception
     * @return array
     */
    protected function handleErrorInfo(Exception $exception) {
        $allTraceList = $exception->getTrace();
        $relList = ["#error:" . $exception->getFile() . "(Line:". $exception->getLine() ."行):"];
        foreach ($allTraceList as $key => $trace) {
            $tempStr = "#" . $key . ":";
            if (array_key_exists('file', $trace)) {
                $tempStr .= $trace['file'] . " ";
            }

            if (array_key_exists('line', $trace)) {
                $tempStr .= '(Line:'.$trace['line'] . "行):";
            }

            if (array_key_exists("class", $trace)) {
                $tempStr .= $trace['class'];
            }

            if (array_key_exists("type", $trace)) {
                $tempStr .= $trace['type'];
            }

            if (array_key_exists("function", $trace)) {
                $tempStr .= $trace['function'] . "(";
                if (array_key_exists("args", $trace)) {
                    foreach ($trace["args"] as $tempArg) {
                        $tempStr .= json_encode($tempArg, 256) . ",";
                    }
                    $tempStr = rtrim($tempStr, ',');
                }
                $tempStr .= ")";
            }

            $relList[] = $tempStr;
        }
        return $relList;
    }
}
